import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/admin',
      redirect: '/admin/dashboard'
    },
    {
      path: '/admin/dashboard',
      name: 'AdminDashboard',
      component: () => import('../views/admin/AdminDashboard.vue'),
      meta: {
        title: '控制面板',
        requiresAuth: true,
        role: 'admin'
      }
    },
    {
      path: '/admin/products',
      name: 'AdminProducts',
      component: () => import('../views/admin/AdminProducts.vue'),
      meta: {
        title: '商品管理',
        requiresAuth: true,
        role: 'admin'
      }
    },
    {
      path: '/admin/users',
      name: 'AdminUsers',
      component: () => import('../views/admin/AdminUsers.vue'),
      meta: {
        title: '用户管理',
        requiresAuth: true,
        role: 'admin'
      }
    },
    {
      path: '/admin/orders',
      name: 'AdminOrders',
      component: () => import('../views/admin/AdminOrders.vue'),
      meta: {
        title: '订单管理',
        requiresAuth: true,
        role: 'admin'
      }
    },
    {
      path: '/admin/messages',
      name: 'AdminMessages',
      component: () => import('../views/admin/AdminMessages.vue'),
      meta: {
        title: '消息管理',
        requiresAuth: true,
        role: 'admin'
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  document.title = to.meta.title ? `${to.meta.title} - 后台管理` : '后台管理'
  
  if (to.meta.requiresAuth === false) {
    return next()
  } else {
    const adminToken = localStorage.getItem("adminToken")
    const userRole = localStorage.getItem("userRole")
    
    if (adminToken && userRole === 'admin') {
      next()
    } else {
      ElMessage.warning("请先登录管理员账号")
      next({ path: "/admin/login" })
    }
  }
})

export default router